'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async login() {
    const { ctx } = this;
    let code=ctx.request.body.code;
    // console.log(code,ctx.service.text,666);
    if(code.toLowerCase()==ctx.session.text.toLowerCase()){//code 码相同
      let result= await ctx.service.user.login(ctx.request.body);
        if(result.length){
          let token=ctx.helper.createToken(result[0].id);
        ctx.body={
          code:1001,
          msg:'登录成功',
          user_id:result[0].id,
          token
        }
        }else{
        ctx.body={
          code:1002,
          msg:'登录失败'
        }
        }
    }else{
      ctx.body={
        code:1002,
        msg:'验证码输入错误'
      }
    }
    
  };
  async registry(){//注册
    let {ctx}=this;
    let result=await ctx.service.user.checkuser(ctx.request.body.username);
    // console.log(ctx.request.body)
    if(result.length){
      ctx.body={
        code:1002,
        msg:'用户已存在'
      }
    }else{
      let id=ctx.helper.createId(ctx.request.body.username)
      let result =await ctx.service.user.registry({
        id,
        ...ctx.request.body
      });
      if(result.affectedRows){
        ctx.body={
          code:1001,
          msg:'注册成功'
        }
      }else{
        ctx.body={
          code:1002,
          msg:'注册失败'
        }
      }
    }
  }
  async getCode(){//验证码
    const {ctx}=this;
    let result= await ctx.helper.createCode();
    if(result){
      ctx.session.text=result.text;//缓存code
      ctx.body={
        code:1001,
        msg:'code 获取成功',
        result
      }
    }else{
      ctx.body={
        code:1002,
        msg:'code 获取失败'
      }
    }
   
  };
}

module.exports = HomeController;
